package qj.util;

import java.util.LinkedList;

/**
 * Created by QuanLA
 * Date: Mar 13, 2006
 * Time: 10:57:56 AM
 */
public class CsvUtil4 {

	/**
	 * 
	 * @param csvData
	 * @return
	 */
//    private static String returnToCsvLine(String[] csvData) {
//        StringBuffer sb = new StringBuffer();
//
//        for (int i = 0; i < csvData.length; i++) {
//            String s = csvData[i];
//            if (i>0) sb.append(',');
//            if (s.length() > 0) sb.append("\"" + s.replaceAll("\"", "\"\"") + "\"");
//        }
//
//        return sb.toString();
//    }

    /**
     *
     * @param sourceLine
     * @return read a line formated as CSV to array
     */
    public static String[] readCSVLine(String sourceLine) {
        LinkedList elements = new LinkedList();
        int rollIndex = -1;
        int lfComma = -1;
        int length = sourceLine.length();

        while (rollIndex < length) {
            if ((rollIndex = sourceLine.indexOf(',', rollIndex + 1)) == -1)
                rollIndex = length;

            System.out.println("lfComma = " + lfComma);
            System.out.println("rollIndex = " + rollIndex);
            elements.add(rejectQuote( sourceLine.substring(lfComma + 1, rollIndex).trim()));

            lfComma = rollIndex;
        }

        String[] strReturn = new String[elements.size()];
        elements.toArray(strReturn);
        return strReturn;
    }

    /**
     *
     * @param rawString
     * @return no Quote mark
     */
    private static String rejectQuote(String rawString) {
        if (rawString==null || rawString.length() == 0 || !(rawString.charAt(0) == '\"'))
            return rawString;
        else {
            rawString = rawString.substring(1, rawString.length() - 1);
            return rawString.replaceAll("\"\"", "\"");
        }
    }
}
